package heap;

import java.util.Arrays;

public class TestHeap {
    public int[] elem;
    public int usedSize;

    public TestHeap() {
        this.elem = new int[10];
    }

    public void init(int[] array) {
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            usedSize++;
        }
    }

    // 创建小根堆
    public void createHeap(int[] array) {
        for (int parent = (usedSize - 2) / 2; parent >= 0; parent--) {
            siftDown(parent, usedSize);
        }
    }

    public void siftDown(int parent, int end) {
        int child = 2 * parent + 1;
        while (child < end) {
            if (child + 1 < end && elem[child] < elem[child + 1]) {
                child++;
            }
            if (elem[child] > elem[parent]) {
                swap(child, parent);
                parent = child;
                child = 2 * parent + 1;
            } else {
                break;
            }
        }
    }

    public void swap(int i, int j) {
        int tmp = elem[i];
        elem[i] = elem[j];
        elem[j] = tmp;
    }

    public void printHeap(int[] array) {
        for (int i = 0; i < array.length - 1; i++) {
            System.out.print(array[i] + " ");
        }
        System.out.println();
    }

    public void offer(int val) {
        if (isFull()) {
            elem = Arrays.copyOf(elem, 2 * elem.length);
        }
        elem[usedSize] = val;
        usedSize++;
        siftUp(usedSize - 1);
    }

    public void siftUp(int child) {
        int parent = (child - 1) / 2;
        while (parent >= 0) {
            if (elem[child] > elem[parent]) {
                swap(child, parent);
                child = parent;
                parent = (child - 1) / 2;
            } else {
                break;
            }
        }
    }

    public boolean isFull() {
        if (usedSize == elem.length) {
            return true;
        }
        return false;
    }

    public int pull() {
        if (isEmpty()) {
            return -1;
        }
        int old = elem[0];
        swap(0, usedSize - 1);
        usedSize--;
        siftDown(0, usedSize);
        return old;
    }

    public boolean isEmpty() {
        return usedSize == 0;
    }

    public void heapSort() {
        // 构建最大堆
        for (int i = (usedSize - 2) / 2; i >= 0; i--) {
            siftDown(i, usedSize);
        }

        // 排序过程
        for (int i = usedSize - 1; i > 0; i--) {
            swap(0, i); // 将堆顶元素与最后一个元素交换
            siftDown(0, i); // 调整剩余部分为最大堆
        }
    }
}